package com.bountytask.config;

import com.alibaba.fastjson.JSONObject;
import com.bountytask.service.impl.InformationServiceImpl;
import com.bountytask.service.impl.LoginServiceImpl;
import com.bountytask.service.impl.TaskServiceImpl;
import com.bountytask.service.impl.UserAndTaskServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * 执行定时任务
 */
@Component
public class ScheduledTasks {
    @Autowired
    private InformationServiceImpl informationService;

    @Autowired
    private UserAndTaskServiceImpl userAndTaskService;

    @Autowired
    private TaskServiceImpl taskService;

    @Resource
    private WebSocketServer webSocketServer;

    @Autowired
    private LoginServiceImpl loginService;

    private String accessToken;

    public String getAccessToken() {
        return accessToken;
    }

    private static ScheduledTasks scheduledTasks;

    @PostConstruct
    public void init(){
        scheduledTasks=this;
        scheduledTasks.informationService=this.informationService;
        scheduledTasks.userAndTaskService=this.userAndTaskService;
        scheduledTasks.taskService=this.taskService;
        scheduledTasks.loginService=this.loginService;
    }

    @Scheduled(cron = "0 0 0/1 * * ?")
    public void testScheduled() throws IOException {

        //获取所有在线的，未截止的任务id
        List<Long> taskIds=scheduledTasks.taskService.getAllOnlineTask();
        Date nowDate = new Date();
        if (taskIds!=null){

            //留下与当前时间相差值为23-24的任务id
            Iterator<Long> iterator = taskIds.iterator();
            while (iterator.hasNext()){
                long diff=scheduledTasks.taskService.getTaskById(iterator.next()).getDeadline().getTime()-nowDate.getTime();
                if (!(diff<=1000*60*60*24 && diff>=1000*60*60*23))
                    iterator.remove();
            }

            //根据任务id去查找该任务下的所有执行者
            //allExecutors:(key:任务id，value:执行者id的数组)，即一个任务对应多个执行者
            HashMap<Long,List<Long>> allExecutors=scheduledTasks.userAndTaskService.getAllExecutor(taskIds);
            Iterator<Map.Entry<Long,List<Long>>> iter = allExecutors.entrySet().iterator();

            //将每条消息保存在information表中
            while (iter.hasNext()){
                Map.Entry<Long,List<Long>>entry=iter.next();
                for (int i = 0; i < entry.getValue().size(); i++)
                    scheduledTasks.informationService.addInformation(0,3,entry.getKey(),entry.getValue().get(i));
            }

            //将map里的所有执行者数组合并在一个数组中
            List<Long> executorsList = new ArrayList<>();
            for (Long key:allExecutors.keySet()){
                List<Long> executors=allExecutors.get(key);
                executorsList.addAll(executors);
                executors.clear();
            }

            //清楚数组中重复的执行者id
            LinkedHashSet<Long> hashSet = new LinkedHashSet<>(executorsList);
            List<Long> executorsListWithoutDuplicates = new ArrayList<>(hashSet);

            //遍历数组，向每个执行者发送信息“距离截止时间还有24小时”
            for (int i = 0; i < executorsListWithoutDuplicates.size(); i++) {
                webSocketServer.sendMessageList(
                        scheduledTasks.informationService.getInfo(0,executorsListWithoutDuplicates.get(i)),
                        executorsListWithoutDuplicates.get(i));
            }
        }
    }

    @Scheduled(cron="0 0,30 * * * ? ")
    public void getAccessTokenUrl(){
        String str=scheduledTasks.loginService.getWxAccessTokenUrl();
        accessToken= JSONObject.parseObject(str).getString("access_token");
    }

}
